package com.swq.java.code.chapter13.code38;

import java.util.concurrent.*;
import java.util.concurrent.locks.*;

public class SyncTest {
    public static void main(String args[]) {
        BlockingQueue<String> queue = new ArrayBlockingQueue<String>(10);
        Producer producer1 = new Producer(queue, "producer1");
        Consumer consumer1 = new Consumer(queue, "consumer1");
        Consumer consumer2 = new Consumer(queue, "consumer2");
    }
}

/**
 * 生产者线程
 */
class Producer extends Thread {
    private BlockingQueue<String> queue;

    public Producer(BlockingQueue<String> queue, String name) {
        super(name);
        this.queue = queue;
        start();  //启动自身生产者线程
    }

    public void run() {
        String goods;
        for (int i = 0; i < 200; i++) {
            try {
//                Thread.sleep(1000);
                goods = "goods" + i;
                queue.put(goods);
                System.out.println(getName() + ": put " + goods + " to the queue");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

/**
 * 消费者线程
 */
class Consumer extends Thread {
    private BlockingQueue<String> queue;

    public Consumer(BlockingQueue<String> queue, String name) {
        super(name);
        this.queue = queue;
        start();  //启动自身消费者线程
    }

    public void run() {
        String goods;
        for (int i = 0; i < 200; i++) {
            try {
//                Thread.sleep(1000);
                goods = queue.take();
                yield();
                System.out.println(getName() + ": take " + goods + " from the queue");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}